import { cloneDeep } from 'lodash'

/**
 * 重置状态
 * @param value 状态值
 * @param resetAfter 重置后执行的回调
 * @param reserve 需要保留的属性
 */
export function useResetState<T extends object>(value: T, resetAfter?: () => void, reserve?: (keyof T)[]) {
  const initialState = cloneDeep(value)
  const state = reactive(cloneDeep(value)) as T & { [key: string]: unknown }
  const reset = () => {
    if (!reserve) {
      reserve = ['pageNum', 'pageSize', 'total'] as (keyof T)[]
    }
    else {
      reserve.push(...['pageNum', 'pageSize', 'total'] as (keyof T)[])
    }
    const preservedState = reserve ? Object.fromEntries(reserve.map(key => [key, state[key]])) : {}
    // 清除所有状态
    Object.keys(state).forEach((key) => {
      delete state[key]
    })
    // 恢复初始状态
    Object.assign(state, initialState)
    // 恢复保留的状态
    if (reserve) {
      Object.assign(state, preservedState)
    }
    resetAfter && resetAfter()
  }
  return [state, reset] as const
}
